package back.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.pojo.InfoEnum;
import common.servlet.BaseServlet;
import common.util.ConstatFinalUtil;
import users.pojo.AAdmins;
import users.service.IUsersDbService;
import users.service.impl.UsersDbServiceImpl;
@WebFilter(urlPatterns = {"/back/*"})
public class Filter02Auth extends BaseServlet implements Filter
{
	private IUsersDbService  userSbService = new UsersDbServiceImpl();
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException
	{
		System.out.println("==AuthFilter==doFilter");
		 HttpServletRequest  request= (HttpServletRequest)req;
		 HttpServletResponse response = (HttpServletResponse) resp ;
		  HttpSession session = request.getSession();
		  /*验证用户是否安全登录，因为只有登录了才会放行adminsSess*/
		  AAdmins adminsSess  = (AAdmins)session.getAttribute("adminsSess");
		  if(adminsSess == null)
		  {
			  this.info = ConstatFinalUtil.INFO_JSON.getString(InfoEnum.INFO_LOGIN_ILLEGAL.getCode() + "") ; 
				session.setAttribute("info", info);
				/* 肯定木有登陆 */
				this.clientRedirect(request, response, "/NoLoginBackServlet?method=login");
				/* 一定return; */
				return ;
		  }
		  /*判断单点登录，根据上次登录的Ip判断
		   * session里面有一份信息
		   * 数据库里面有一份信息
		   * */
		  /*根据Id查询数据库里面的最新的信息*/
		   Map<String,Object>condMap = new  HashMap<String,Object>();
		   condMap.clear();
		   condMap.put("id", adminsSess.getId());
		   AAdmins adminsDb = this.userSbService.findOneAdminsService(condMap);
		   if(!adminsDb.getLastLoginIp().equalsIgnoreCase(adminsSess.getLastLoginIp()))
			{
				/* 说明你的账号已经在其他地方登陆,强制下线 */
				this.info = ConstatFinalUtil.INFO_JSON.getString(InfoEnum.INFO_REMOTE_LOGIN.getCode() + "") ; 
				session.setAttribute("info", info);
				session.removeAttribute("lastLoginTime");
				session.removeAttribute("adminsSess");
				this.clientRedirect(request, response, "/NoLoginBackServlet?method=login");
				return ; 
			}
		  /*放行*/
		  chain.doFilter(request,response);
	}
	
}
